package model

import (
	"log"
	"strings"
	"time"
)

type Message struct {
	Id         int       `json:"id" xorm:"int(3) pk not null autoincr 'Id'`
	Content    string    `json:"content" xorm:"varchar(40) not null"`
	Email      string    `xorm:"varchar(80) not null"`
	Name       string    `json:"author" xorm:"varchar(20) default 'SYSTEM' 'Name'"`
	CreateDate time.Time `json:"time" xorm:"datetime created 'CreateDate'"`
	Page       `json:"-" xorm:"-"`
}

func (self *Message) GetMessageById() (*Message, error) {
	link := &Message{Id: self.Id}
	_, err := orm.Get(link)
	return link, err
}

func (self *Message) Insert() error {
	session := orm.NewSession()
	defer session.Close()
	_, err := session.InsertOne(self)
	return err
}

func (self *Message) SearchByPage(p int, searchValue string) ([]Message, int, error) {
	total, err := orm.Count(self)
	log.Printf("查询出的总数%d\n", total)
	var msgs []Message
	if strings.TrimSpace(searchValue) == "" {
		err = orm.OrderBy("CreateDate desc").Limit(10, 10*(p-1)).Find(&msgs, self)
	} else {
		err = orm.Where("Content like '%"+searchValue+"%'").OrderBy("CreateDate desc").Limit(10, 10*(p-1)).Find(&msgs, self)
	}
	return msgs, int(total), err
}
